package com.now.printer.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import androidx.core.content.FileProvider;

import com.now.printer.R;

import org.xutils.common.util.LogUtil;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class FileUtils {

    /**
     * 文档类型
     */
    public static final int TYPE_ALL = 0;
    public static final int TYPE_DOC = 1;
    public static final int TYPE_PDF = 2;

    public static final int TYPE_PPT = 4;

    public static final int TYPE_XLS = 3;
    public static final int TYPE_TXT = 5;
    public static final int TYPE_PIC = 6;

    public static final int TYPE_ALL_DOCS = 7;

    public static String getCurrentAppPath(Context context) {
        String appPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + context.getString(R.string.app_name);
        File file = new File(appPath);
        if (!file.exists()) file.mkdirs();
        return appPath;
    }

    /**
     * 判断文件是否存在
     *
     * @param path 文件的路径
     * @return
     */
    public static boolean isExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    //获取全部类型
    public static int getFileTypeAll(String path) {
        path = path.toLowerCase();
        if (path.endsWith(".doc") || path.endsWith(".docx") || path.endsWith(".xls") || path.endsWith(".xlsx")
                || path.endsWith(".pdf") || path.endsWith(".ppt") || path.endsWith(".pptx") || path.endsWith(".txt") || path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
            return TYPE_ALL;
        } else {
            return -1;
        }
    }


    //获取文件类型
    public static int getFileType(String path) {
        path = path.toLowerCase();
        if (path.endsWith(".doc") || path.endsWith(".docx")) {
            return TYPE_DOC;
        } else if (path.endsWith(".xls") || path.endsWith(".xlsx")) {
            return TYPE_XLS;
        } else if (path.endsWith(".ppt") || path.endsWith(".pptx")) {
            return TYPE_PPT;
        } else if (path.endsWith(".pdf")) {
            return TYPE_PDF;
        } else if (path.endsWith(".txt")) {
            return TYPE_TXT;
        } else if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
            return TYPE_PIC;
        } else {
            return -1;
        }
    }

    /**
     * 通过文件名获取文件图标
     */
    public static int getFileIconByPath(String path) {
        path = path.toLowerCase();
        int iconId = R.mipmap.ic_launcher;
        if (path.endsWith(".txt")) {
            iconId = R.mipmap.icon_txt;
        } else if (path.endsWith(".doc") || path.endsWith(".docx")) {
            iconId = R.mipmap.icon_doc;
        } else if (path.endsWith(".xls") || path.endsWith(".xlsx")) {
            iconId = R.mipmap.icon_excel;
        } else if (path.endsWith(".ppt") || path.endsWith(".pptx")) {
            iconId = R.mipmap.icon_ppt;
        } else if (path.endsWith(".htm") || path.endsWith(".html")) {
            iconId = R.mipmap.icon_html;
        } else if (path.endsWith(".pdf")) {
            iconId = R.mipmap.icon_pdf;
        }
        return iconId;
    }

    /**
     * 是否是图片文件
     */
    public static boolean isPicFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        path = path.toLowerCase();
        if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png")) {
            return true;
        }
        return false;
    }


    /**
     * 判断SD卡是否挂载
     */
    public static boolean isSDCardAvailable() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 从文件的全名得到文件的拓展名
     *
     * @param filename
     * @return
     */
    public static String getExtFromFilename(String filename) {
        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(dotPosition + 1, filename.length());
        }
        return "";
    }

    /**
     * 读取文件的修改时间
     *
     * @param f
     * @return
     */
    public static String getModifiedTime(File f) {
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        // System.out.println("修改时间[2] " + formatter.format(cal.getTime()));
        // 输出：修改时间[2] 2009-08-17 10:32:38
        return formatter.format(cal.getTime());
    }

    /**
     * 　　* 转换文件大小
     * 　　* @param fileS
     * 　　* @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

//    public static String getMimeType(String filePath) {
        //使用系统API，获取URL路径中文件的后缀名（扩展名）
//        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
//        String type = "";
//        if (!TextUtils.isEmpty(extension)) {
//            //使用系统API，获取MimeTypeMap的单例实例，然后调用其内部方法获取文件后缀名（扩展名）所对应的MIME类型
//            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
//        }
//        LogUtil.i("MIME 类型为：" + type);
//        return type;

//        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//        String mime = "*/*";
//        if (filePath != null) {
//            try {
//                mmr.setDataSource(filePath);
//                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
//            } catch (RuntimeException e) {
//                e.printStackTrace();
//                LogUtil.e("getMimeType ： " + e.getMessage());
//                return mime;
//            }
//        }
//        return mime;
//    }

    /**
     * 获得文件的mimeType
     * @param file
     * @return
     */
    public static String getMIMEType(File file) {
        String type = "*";
        if(file == null) return type;
        String fName = file.getName();
        // 取得扩展名
        String end = fName.substring(fName.lastIndexOf("."),
                fName.length()).toLowerCase();
        if (end.equals("")) return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }

        return type;
    }

    private static String[][] MIME_MapTable = {
            //{后缀名， MIME类型}
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            //{".xml", "text/xml"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/zip"},
            {"", "*/*"}
    };

    public static Uri getFileUri(Context context, File file){
        Uri uri;
        // 低版本直接用 Uri.fromFile
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        }else {
            //  使用 FileProvider 会在某些 app 下不支持（在使用FileProvider 方式情况下QQ不能支持图片、视频分享，微信不支持视频分享）
            uri = FileProvider.getUriForFile(context,
                    "gdut.bsx.videoreverser.fileprovider",
                    file);

            ContentResolver cR = context.getContentResolver();
            if (uri != null && !TextUtils.isEmpty(uri.toString())) {
                String fileType = cR.getType(uri);
// 使用 MediaStore 的 content:// 而不是自己 FileProvider 提供的uri，不然有些app无法适配
//                if (!TextUtils.isEmpty(fileType)){
//                    if (fileType.contains("video/")){
//                        uri = getVideoContentUri(context, file);
//                    }else if (fileType.contains("image/")){
//                        uri = getImageContentUri(context, file);
//                    }else if (fileType.contains("audio/")){
//                        uri = getAudioContentUri(context, file);
//                    }
//                }
            }
        }
        return uri;
    }
}
